package org.example.beetlsql.mutiple.conf;

import com.zaxxer.hikari.HikariDataSource;
import org.beetl.sql.core.SQLManager;
import org.beetl.sql.ext.DBInitHelper;
import org.beetl.sql.starter.SQLManagerCustomize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;

import javax.sql.DataSource;

@Configuration
public class MutipleDataSourceConfig {
    @Autowired
    ApplicationContext ctx;

    @Bean(name = "ds1")
    public DataSource datasource(Environment env) {
        HikariDataSource ds = new HikariDataSource();
        ds.setJdbcUrl(env.getProperty("spring.datasource1.url"));
        ds.setUsername(env.getProperty("spring.datasource1.username"));
        ds.setPassword(env.getProperty("spring.datasource1.password"));
        ds.setDriverClassName(env.getProperty("spring.datasource1.driver-class-name"));
        return ds;
    }

	@Bean(name = "ds2")
	public DataSource datasource2(Environment env) {
		HikariDataSource ds = new HikariDataSource();
		ds.setJdbcUrl(env.getProperty("spring.datasource2.url"));
		ds.setUsername(env.getProperty("spring.datasource2.username"));
		ds.setPassword(env.getProperty("spring.datasource2.password"));
		ds.setDriverClassName(env.getProperty("spring.datasource2.driver-class-name"));
		return ds;
	}


    /**
     * 自动初始化所有数据
     * @param ds2
     * @return
     */
    @Bean
    public SQLManagerCustomize mySQLManagerCustomize(DataSource ds2){
        return new SQLManagerCustomize(){
            @Override
            public void customize(String sqlMangerName, SQLManager manager) {
            	//初始化sql，这里也可以对sqlManager进行修改
                if(sqlMangerName.equals("sqlManager1")){
                    DBInitHelper.executeSqlScript(manager, "db/schema1.sql");
                }else  if(sqlMangerName.equals("sqlManager2")){
                    DBInitHelper.executeSqlScript(manager, "db/schema2.sql");
                }else{
                    throw new UnsupportedOperationException(sqlMangerName);
                }

            }
        };
    }
}
